//
//  SHOrderDetailView.swift
//  ServiceHelper
//
//  Created by Stan Wu on 15/4/13.
//  Copyright (c) 2015年 Stan Wu. All rights reserved.
//

import UIKit
import AVFoundation

protocol SHOrderDetailDelegate{
    func orderUpdated(order: NSDictionary?)
}

class SHOrderDetailView: UIView,UITableViewDelegate,UITableViewDataSource,SWImageViewDelegate,AVAudioPlayerDelegate,UIPopoverControllerDelegate,UIAlertViewDelegate {
    var tvDetail: UITableView!
    var player: AVAudioPlayer?
    var btnPlay: UIButton?
    var selectedDate: NSDate?
    var pop: UIPopoverController!
    
    var orderInfo: NSDictionary?{
        didSet{
            if orderInfo != nil{
                tvDetail.hidden = false
            }else{
                tvDetail.hidden = true
            }
            
            if let audio = orderInfo?.objectForKey("audio") as! String!{
                SWUtils.RunOnBackgroundThread({ () -> Void in
                    autoreleasepool({ () -> () in
                        let filename = audio.lastPathComponent
                        var data: NSData?
                        if NSFileManager.defaultManager().fileExistsAtPath(filename.temporaryPath()){
                            data = NSData(contentsOfFile: filename.temporaryPath())
                        }else{
                            data = NSData(contentsOfURL: NSURL(string: audio)!)
                            data?.writeToFile(filename.temporaryPath(), atomically: false)
                        }
                        
                        if data != nil{
                            if self.player != nil{
                                self.player!.stop()
                            }
                            
                            self.player = try? AVAudioPlayer(data: data!)
                            self.player?.delegate = self
                            self.player?.prepareToPlay()
                            SWUtils.RunOnMainThread({ () -> Void in
                                self.tvDetail.reloadData()
                            })
                        }
                        
                    })
                })
                
            }else{
                if self.player != nil{
                    self.player!.stop()
                }
                
                self.player = nil
                
            }
            
            btnPlay?.selected = false
            tvDetail.reloadData()
            updateButtonStatus()
        }
    }
    
    var delegate: SHOrderDetailDelegate?
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        tvDetail = UITableView(frame: CGRectMake(20, 18, frame.size.width-20*2, 570))
        tvDetail.delegate = self
        tvDetail.dataSource = self
        tvDetail.backgroundColor = UIColor.clearColor()
        tvDetail.separatorStyle = .None
        
        var btn = UIButton(type: .Custom)
        btn.frame = CGRectMake(54+50, 610, 150, 44)
        btn.setBackgroundImage(UIImage.colorImage(UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
        btn.setTitle("预约确认", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(18)
        btn.setTitleColor(UIColor.whiteColor(), forState:.Normal)
        btn.addTarget(self, action: #selector(SHOrderDetailView.confirmClicked), forControlEvents: .TouchUpInside)
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 4
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1).CGColor
        self.addSubview(btn)
        btn.tag = 1000
        
//        btn = UIButton.buttonWithType(.Custom) as! UIButton
//        btn.frame = CGRectMake(54+204, 610, 150, 44)
//        btn.setBackgroundImage(UIImage.colorImage(UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
//        btn.setTitle("预约取消", forState: .Normal)
//        btn.titleLabel?.font = UIFont.systemFontOfSize(18)
//        btn.setTitleColor(UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1), forState:.Normal)
//        btn.addTarget(self, action: "refuseClicked", forControlEvents: .TouchUpInside)
//        btn.clipsToBounds = true
//        btn.layer.cornerRadius = 4
//        btn.layer.borderWidth = 0.5
//        btn.layer.borderColor = UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1).CGColor
//        self.addSubview(btn)
//        btn.tag = 1001
        
        btn = UIButton(type: .Custom)
        btn.frame = CGRectMake(54+204*2-100, 610, 150, 44)
        btn.setBackgroundImage(UIImage.colorImage(UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
        btn.setTitle("预约变更", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(18)
        btn.setTitleColor(UIColor(white: 0.53, alpha: 1), forState:.Normal)
        btn.addTarget(self, action: #selector(SHOrderDetailView.adjustClicked(_:)), forControlEvents: .TouchUpInside)
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 4
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor(white: 0.53, alpha: 1).CGColor
        self.addSubview(btn)
        btn.tag = 1002
        
        
        
        
        self.addSubview(tvDetail)
    }
    
    func confirmClicked(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.orderInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.acceptOrder(NSDictionary(object: order_id,forKey: "order_id"))
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.orderInfo!) as NSMutableDictionary
                                mut.setObject("3", forKey: "order_status")
                                
                                self.orderInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.updateButtonStatus()
                    })
                }
            })
        }
    }
    
    
    
    func refuseClicked(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.orderInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.refuseOrder(NSDictionary(object: order_id,forKey: "order_id"))
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.orderInfo!) as NSMutableDictionary
                                mut.setObject("2", forKey: "order_status")
                                
                                self.orderInfo = NSDictionary(dictionary: mut)
                                
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.updateButtonStatus()
                    })
                    
                }
                })
                
        }
    }
    
    func adjustClicked(sender: UIButton){
        let vc = UIViewController()
        let picker = UIDatePicker()
        picker.minuteInterval = 30
        
        picker.datePickerMode = UIDatePickerMode.DateAndTime
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        let minday = formatter.dateFromString(formatter.stringFromDate(NSDate().dateByAddingTimeInterval(24*3600)))
        let maxday = formatter.dateFromString(formatter.stringFromDate(NSDate().dateByAddingTimeInterval(24*3600*3)))
        
        picker.minimumDate = minday?.dateByAddingTimeInterval(9*3600)
        picker.maximumDate = maxday?.dateByAddingTimeInterval(17*3600)
        picker.tag = 100
        
        picker.addTarget(self, action: #selector(SHOrderDetailView.dateChanged(_:)), forControlEvents: .ValueChanged)
        
        
        
        vc.view.addSubview(picker)
        
        pop = UIPopoverController(contentViewController: vc)
        pop.delegate = self
        pop.popoverContentSize = CGSizeMake(320, 218)
        pop.presentPopoverFromRect(sender.frame, inView: sender.superview!, permittedArrowDirections: .Any, animated: true)
        
        
    }
    
    func dateChanged(sender: UIDatePicker){
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd";
        
        
        let baseDate = formatter.dateFromString(formatter.stringFromDate(sender.date)) as NSDate!
        
        if sender.date.timeIntervalSinceDate(baseDate.dateByAddingTimeInterval(9*3600)) >= 0 && baseDate.dateByAddingTimeInterval(17*3600).timeIntervalSinceDate(sender.date) >= 0{
            
        }else if sender.date.timeIntervalSinceDate(baseDate.dateByAddingTimeInterval(9*3600)) < 0{
            sender.date = baseDate.dateByAddingTimeInterval(9*3600)
        }else{
            sender.date = baseDate.dateByAddingTimeInterval(17*3600)
        }

    }
    
    func updateButtonStatus(){
        if let status = orderInfo?.objectForKey("order_status")?.intValue{
            if 1==status{
                for i in 0 ..< 3{
                    let btn = self.viewWithTag(1000+i)
                    btn?.hidden = false
                }
            }else{
                for i in 0 ..< 3{
                    let btn = self.viewWithTag(1000+i)
                    btn?.hidden = true
                }
            }
        }else{
            for i in 0 ..< 3{
                let btn = self.viewWithTag(1000+i)
                btn?.hidden = true
            }
        }
        
        tvDetail.reloadData()
        delegate?.orderUpdated(orderInfo)
    }

    func imageClicked(sender: UIButton){
        
        
        let index = sender.superview!.tag % 100
        
        if let photoList = orderInfo?.objectForKey("photo_list") as! [NSDictionary]!{
            if index < photoList.count{
                let vc = UIViewController()
                vc.view.frame = CGRectMake(0, 0, 500, 500)
                let imgv = SWImageView(frame: CGRectMake(0, 0, 500, 500))
                vc.view.addSubview(imgv)
                
                if let originalURL = photoList[index].objectForKey("original_url") as? String{
                    imgv.loadURL(originalURL)
//<<<<<<< HEAD
//                    
//                    var pop = UIPopoverController(contentViewController: vc)
//=======
                    pop = nil
                    pop = UIPopoverController(contentViewController: vc)
//>>>>>>> d50134bd0a5bcc4bec1d3d0fe719f14d79f68d95
                    pop.popoverContentSize = CGSizeMake(500, 500)
                    
                    pop.presentPopoverFromRect(sender.frame, inView: sender.superview!, permittedArrowDirections: .Any, animated: true)
                }
                
            }
        }
        
        
        
    }
    
    func audioClicked(){
        if let audioPlayer = player{
            if audioPlayer.playing{
                audioPlayer.stop()
                btnPlay?.selected = false
            }else{
                audioPlayer.play()
                btnPlay?.selected = true
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //  MARK: - UITableView Delegate & Data Source
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var identifiers = [["OrderCreator","OrderDetail"],["CarInfo"]]
        
        let identifier = identifiers[indexPath.section][indexPath.row]
        
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!
        
        if cell==nil{
            cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
            switch indexPath.section{
            case 0:
                switch indexPath.row{
                case 0:
                    var titles = "预约人，联系电话，预约时间，发起时间，预约项目，服务方式，预约状态".componentsSeparatedByString("，")
                    for i in 0 ..< titles.count{
                        let col = i % 2
                        let row = i / 2
                        var lbl = UILabel.create(CGRectMake(CGFloat(29+304*col), CGFloat(27+35*row), 70, 17), font: UIFont.systemFontOfSize(16), textColor: UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1))
                        lbl.text = titles[i]
                        cell.contentView.addSubview(lbl)
                        
                        lbl = UILabel.create(CGRectMake(CGFloat(29+304*col+80), CGFloat(27+35*row), 200, 17), font: UIFont.systemFontOfSize(16), textColor: UIColor.blackColor())
                        lbl.text = titles[i]
                        lbl.tag = 100+i
                        cell.contentView.addSubview(lbl)
                    }
                    
                    let line = UIView(frame: CGRectMake(0, 175.5, tvDetail.frame.size.width, 0.5))
                    line.backgroundColor = UIColor(white: 0.88, alpha: 1)
                    cell.contentView.addSubview(line)
                    
                case 1:
                    var lbl = UILabel.create(CGRectMake(29, 19, 70, 17), font: UIFont.systemFontOfSize(16), textColor: UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1))
                    lbl.text = "详情描述"
                    cell.contentView.addSubview(lbl)
                    
                    lbl = UILabel.create(CGRectMake(29+80, 18, tvDetail.frame.size.width-109-29, 0), font: UIFont.systemFontOfSize(17), textColor: UIColor.blackColor())
                    lbl.numberOfLines = 0
                    lbl.tag = 100
                    cell.contentView.addSubview(lbl)
                    
                    for i in 0 ..< 6{
                        let imgv = SWImageView(frame: CGRectMake(29+CGFloat(84*i), 0, 71, 71))
                        imgv.clipsToBounds = true
                        imgv.layer.borderWidth = 0.5
                        imgv.layer.borderColor = UIColor(red: 0.8, green: 0.82, blue: 0.85, alpha: 1).CGColor
                        imgv.layer.cornerRadius = 4
                        imgv.delegate = self
                        imgv.tag = 200+i
                        cell.contentView.addSubview(imgv)
                        
                        let btn = UIButton(type: .Custom)
                        btn.frame = imgv.bounds
                        imgv.userInteractionEnabled = true
                        btn.addTarget(self, action: #selector(SHOrderDetailView.imageClicked(_:)), forControlEvents: .TouchUpInside)
                        imgv.addSubview(btn)
                    }
                    
                    let btn = UIButton(type: .Custom)
                    btn.setBackgroundImage(UIImage(named: "OrderIconPlay"), forState: .Normal)
                    btn.setBackgroundImage(UIImage(named: "OrderIconPause"), forState: .Selected)
                    btn.sizeToFit()
                    btn.frame = CGRectMake(tvDetail.frame.size.width-btn.frame.size.width+10, 13, btn.frame.size.width, btn.frame.size.height)
                    btn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
                    btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
                    btn.tag = 300
                    btn.addTarget(self, action: #selector(SHOrderDetailView.audioClicked), forControlEvents: .TouchUpInside)
                    cell.contentView.addSubview(btn)
                    
                    btnPlay = btn
                    
                default:()
                }
            case 1:
                switch indexPath.row{
                case 0:
                    var titles = "车辆型号，生产日期，发动机号".componentsSeparatedByString("，")
                    for i in 0 ..< 3{
                        var lbl = UILabel.create(CGRectMake(29, CGFloat(24+35*i), 70, 17), font: UIFont.systemFontOfSize(16), textColor: UIColor(white: 0.44, alpha: 1))
                        lbl.text = titles[i]
                        cell.contentView.addSubview(lbl)
                        
                        lbl = UILabel.create(CGRectMake(CGFloat(110), CGFloat(23+35*i), 200, 18), font: UIFont.systemFontOfSize(17), textColor: UIColor.blackColor())
                        lbl.text = titles[i]
                        lbl.tag = 100+i
                        cell.contentView.addSubview(lbl)
                    }
                default:()
                }
            default:()
            }
        }
        
        switch indexPath.section{
        case 0:
            switch indexPath.row{
            case 0:
                let lblName = cell.contentView.viewWithTag(100) as! UILabel!
                let lblPhone = cell.contentView.viewWithTag(101) as! UILabel!
                let lblOrderTime = cell.contentView.viewWithTag(102) as! UILabel!
                let lblCreateTime = cell.contentView.viewWithTag(103) as! UILabel!
                let lblOrderType = cell.contentView.viewWithTag(104) as! UILabel!
                
                let lblServiceType = cell.contentView.viewWithTag(105) as! UILabel!
                let lblOrderStatus = cell.contentView.viewWithTag(106) as! UILabel!
                
                lblName.text = orderInfo?.objectForKey("nickname") as! String?
                lblOrderTime.text = orderInfo?.objectForKey("order_time") as! String?
                lblCreateTime.text = orderInfo?.objectForKey("create_time") as! String?
                
                
                if let phone = orderInfo?.objectForKey("order_phone") as! String!{
                    lblPhone.text = phone
                }else if let phone = orderInfo?.objectForKey("phone") as! String!{
                    lblPhone.text = phone
                }else{
                    lblPhone.text = nil
                }
                
                if let orderType = orderInfo?.objectForKey("order_type")?.intValue{
                    if 1==orderType{
                        lblOrderType.text = "保养"
                    }else{
                        lblOrderType.text = "维修"
                    }
                }else{
                    lblOrderType.text = nil
                }
                
                if let pickType = orderInfo?.objectForKey("pick_type")?.intValue{
                    if 1==pickType{
                        lblServiceType.text = "送车到店"
                    }else{
                        lblServiceType.text = "上门取车"
                    }
                }else{
                    lblServiceType.text = nil
                }
                
                var status: String!
                if let order_status = orderInfo?.objectForKey("order_status")?.integerValue{
                    
                    let statuses = "，已发起，已拒绝，已受理，已完成服务未评价，已评价".componentsSeparatedByString("，")
                    switch order_status{
                    case 2:
                        if let is_expired = orderInfo?.objectForKey("is_expired")?.intValue{
                            if is_expired > 0{
                                status = "已超时"
                            }else{
                                status = "已拒绝"
                            }
                        }
                    case 1,3,4,5:
                        status = statuses[order_status]
                    default:()
                    }
                }
                lblOrderStatus.text = status
                
                
            case 1:
                let lblContent = cell.contentView.viewWithTag(100) as! UILabel!
                let btn = cell.contentView.viewWithTag(300) as! UIButton!
                
                if let content = orderInfo?.objectForKey("content") as! String!{
                    lblContent.text = content
                }else{
                    lblContent.text = nil
                }
                
                if player != nil{
                    btn.hidden = false
                    //\\
                    
//                    let audio = orderInfo?.objectForKey("audio") as! String!
                    //\\
                    
//                    var path = audio.lastPathComponent.temporaryPath()
 
 
                    
                    btn.setTitle(String(format: "%.0lf''", player!.duration), forState: .Normal)
                    
                }else{
                    btn.hidden = true
                }
                
                
                let size = lblContent.sizeThatFits(CGSizeMake(lblContent.frame.size.width, CGFloat(FLT_MAX)))
                var frame = lblContent.frame
                frame.size.height = size.height
                lblContent.frame = frame
                
                let y = frame.origin.y + frame.size.height + 28
                
                if let photoList = orderInfo?.objectForKey("photo_list") as! [NSDictionary]!{
                    for i in 0 ..< 6{
                        let imgv = cell.contentView.viewWithTag(200+i) as! SWImageView
                        frame = imgv.frame
                        frame.origin.y = y
                        imgv.frame = frame
                        if i < photoList.count{
                            imgv.hidden = false
                            imgv.loadURL(photoList[i].objectForKey("small_url") as? String)
                        }else{
                            imgv.hidden = true
                            imgv.image = nil
                        }
                    }
                }else{
                    for i in 0 ..< 6{
                        let imgv = cell.contentView.viewWithTag(200+i) as! SWImageView
                        imgv.image = nil
                        imgv.hidden = true
                    }
                }
                
                
                
            default:()
            }
        case 1:
            switch indexPath.row{
            case 0:
                let lblModel = cell.contentView.viewWithTag(100) as! UILabel!
                let lblCreateTime = cell.contentView.viewWithTag(101) as! UILabel!
                let lblVIN = cell.contentView.viewWithTag(102) as! UILabel!
                
                if let model = orderInfo?.objectForKey("car_info")?.objectForKey("series_name") as! String!{
                    lblModel.text = model
                }else{
                    lblModel.text = nil
                }
                
                if let create_time = orderInfo?.objectForKey("car_info")?.objectForKey("scan_time") as! String!{
                    lblCreateTime.text = create_time
                }else{
                    lblCreateTime.text = nil
                }
                
                if let vin = orderInfo?.objectForKey("car_info")?.objectForKey("vin") as! String!{
                    lblVIN.text = vin
                }else{
                    lblVIN.text = nil
                }
            default:()
            }
        default:()
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.section{
        case 0:
            switch indexPath.row{
            case 0:
                return 176
            case 1:
                return 152
            default:()
            }
        case 1:
            switch indexPath.row{
            case 0:
                return 128
            default:()
            }
        default:()
        }
        
        return 0.0
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section{
        case 0:
            return 2
        case 1:
            return 1
        default:()
        }
        
        return 0
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if 1==section{
            let v = UIView()
            
            let lbl = UILabel.create(CGRectMake(0, 20, 100, 16), font: UIFont.systemFontOfSize(15), textColor: UIColor(white: 0.42, alpha: 1))
            lbl.text = "资料"
            
            v.addSubview(lbl)
            
            return v
        }else{
            return nil
        }
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if 1==section{
            return 48
        }else{
            return 0
        }
    }
    
//  MARK: - SWImageView Delegate
    func swImageViewLoadFinished(imgv: SWImageView) {
        
    }
    //  MARK: - AVAudioPlayer Delegate
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        btnPlay?.selected = false
    }
    
    //  MARK: - UIPopoverController Delegate
    func popoverControllerShouldDismissPopover(popoverController: UIPopoverController) -> Bool {
        return true
    }
    
    func popoverControllerDidDismissPopover(popoverController: UIPopoverController) {
        let picker: UIDatePicker = popoverController.contentViewController.view.viewWithTag(100) as! UIDatePicker
        
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        if let orderTime = orderInfo?.objectForKey("order_time") as? String{
            let date = formatter.dateFromString(orderTime)
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            
            if formatter.stringFromDate(picker.date) != formatter.stringFromDate(date!){
                selectedDate = picker.date

                let alert = UIAlertView(title: nil, message: "是否确定要变更预约时间？", delegate: self, cancelButtonTitle: "取消")
                alert.addButtonWithTitle("变更时间")
                alert.tag = 100
                alert.show()
            }
        }
                
    }
    
    
    // MARK: - UIAlertView Delegate
    func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
        let buttonTitle = alertView.buttonTitleAtIndex(buttonIndex)
        if buttonTitle == "变更时间"{
            SWUtils.RunOnBackgroundThread { () -> Void in
                autoreleasepool({ () -> () in
                    let dict = SHDataProvider.adjustOrder(["order_id":self.orderInfo?.objectForKey("order_id") as! String!,"order_time":String(format: "%.0lf",self.selectedDate!.timeIntervalSince1970)])
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                
                                let mut = NSMutableDictionary(dictionary: self.orderInfo!) as NSMutableDictionary
                                mut.setObject("3", forKey: "order_status")
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                                mut.setObject(formatter.stringFromDate(self.selectedDate!), forKey: "order_time")
                                
                                self.orderInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.updateButtonStatus()
                    })
                    
                })
            }
        }
    }
}
